package com.lingshu.app.ui.register;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;

import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.lingshu.app.BR;
import com.lingshu.app.R;
import com.lingshu.app.base.BaseFragment;
import com.lingshu.app.base.adapter.CommonAdapter;
import com.lingshu.app.config.Constants;
import com.lingshu.app.config.LoadState;
import com.lingshu.app.databinding.FragmentRegisterBinding;
import com.lingshu.app.model.enums.ImagePart;
import com.lingshu.app.model.register.RegisterImageChangeRequest;
import com.lingshu.app.model.register.RegisterImageResponse;
import com.lingshu.app.model.register.RegisterQaRequest;
import com.lingshu.app.model.register.RegisterScreenshotResponse;
import com.lingshu.app.model.register.RegisterScreenshotSaveRequest;
import com.lingshu.app.network.CustomDisposable;
import com.lingshu.app.network.RetrofitMobileClient;
import com.lingshu.app.service.RegisterService;
import com.lingshu.app.ui.report.ReportActivity;
import com.lingshu.app.utils.PathUtils;
import com.lingshu.app.utils.QaFailedUtils;
import com.lingshu.core.utils.KLog;
import com.lingshu.customview.spanner.MultiSpinnerSearch;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;

import cn.hutool.core.io.FileUtil;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/1/3 14:15
 * @Description
 */
@AndroidEntryPoint
public class RegisterFragment extends BaseFragment<FragmentRegisterBinding, RegisterViewModel> {
    private static final String TAG = RegisterFragment.class.getName();
    CommonAdapter<RegisterImageResponse> imageAdapter;
    CommonAdapter<RegisterScreenshotResponse> screenshotAdapter;
    AlertDialog dialog;
    Matrix matrix = new Matrix();

    float[] myValues = new float[9];

    /**
     * 获取当前页面的布局资源ID
     *
     * @return 布局资源ID
     */
    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_register;
    }

    /**
     * 初始化ViewModel
     */
    @Override
    protected void initViewModel() {
        viewModel = new ViewModelProvider(this).get(RegisterViewModel.class);
    }

    /**
     * 绑定ViewModel
     */
    @Override
    protected void bindViewModel() {
        dataBinding.setViewModel(viewModel);
    }

    /**
     * 初始化
     */
    @Override
    protected void init() {
        viewModel.initData();
        initImageRecyclerView();
        initScreenshotRecyclerView();
        btnClickBind();
        observeData();
    }

    /**
     * 监控数据变化
     */
    private void observeData() {
        viewModel.register.observe(context, list -> {
            viewModel.loadState.postValue(LoadState.SUCCESS);
            if (!list.getCanChangePart()) {
                dataBinding.btnModify.setVisibility(View.GONE);
            }
        });
        viewModel.imageList.observe(context, list -> {
            if (list.size() > 0) {
                viewModel.imageListInit(list, context);
                imageAdapter.onItemDataChanged(list);
            }
        });
        viewModel.screenshotList.observe(context, list -> {
            if (list.size() > 0) {
                viewModel.screenshotListInit(list, context);
                screenshotAdapter.onItemDataChanged(list);
            }
        });
        viewModel.selectedImage.observe(context, imageInfo -> {
            dataBinding.sbNumber.setMax(imageInfo.getFrameCount());
            dataBinding.imageViewDraw.setImageId(imageInfo.getId());
            dataBinding.imageViewDraw.setPixelSpacing(imageInfo.getPixelSpacing());
            if (FileUtil.exist(imageInfo.getLocalPath())) {
                viewModel.setDicomSelected(imageInfo);
            }
        });
        viewModel.screenshot.observe(context, screenshot -> {
            String sourceFilePath = getContext().getExternalCacheDir() + "/temp/dicom/" + new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE).format(viewModel.register.getValue().getCreateTime()) + "/" + screenshot.getRegisterId() + "/" + screenshot.getImageId() + "/" + screenshot.getCurrentFrame() + ".jpeg";
            String destinationFilePath = getContext().getExternalCacheDir() + "/temp/screenshot/" + new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE).format(viewModel.register.getValue().getCreateTime()) + "/" + screenshot.getRegisterId() + "/" + screenshot.getImageId() + "_" + screenshot.getCurrentFrame() + ".jpeg";
            if (!new File(destinationFilePath).exists()) {
                Observable.fromCallable(() -> viewModel.copyFile(sourceFilePath, destinationFilePath)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        screenshot.setLocalStoragePath(destinationFilePath);
                        viewModel.downloadScreenshot(screenshot, false, false, context);
                        viewModel.addScreenshotToCollection(screenshot);
                    }
                });
            } else {
                screenshot.setLocalStoragePath(destinationFilePath);
                viewModel.downloadScreenshot(screenshot, false, false, context);
                viewModel.addScreenshotToCollection(screenshot);
            }
        });
    }

    /**
     * 影像集合绑定
     */
    private void initImageRecyclerView() {
        imageAdapter = new CommonAdapter<RegisterImageResponse>(R.layout.item_register_image, BR.imageItem) {
            @Override
            public void addListener(View root, RegisterImageResponse itemData, int position) {
                super.addListener(root, itemData, position);
                root.findViewById(R.id.btn_image_download).setOnClickListener(v -> {
                    ImageView imageView = root.findViewById(R.id.btn_image_loading);
                    Glide.with(imageView.getContext()).load(R.drawable.loading).into(imageView);
                    viewModel.downloadImage(itemData, true, context);
                });
            }

            @Override
            public void clickListener(View root, RegisterImageResponse itemData, int position) {
                root.findViewById(R.id.btn_image_play).setOnClickListener(v -> {
                    dataBinding.sbNumber.setMax(itemData.getFrameCount());
                    dataBinding.sbNumber.setProgress(1);
                    viewModel.setDicomSelected(itemData);
                    changeImagePath(itemData, 1);
                });
            }
        };
        dataBinding.recyclerViewImageList.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
        dataBinding.recyclerViewImageList.setHasFixedSize(true);
        dataBinding.recyclerViewImageList.setAdapter(imageAdapter);
    }

    /**
     * 截图数据绑定
     */
    private void initScreenshotRecyclerView() {
        screenshotAdapter = new CommonAdapter<RegisterScreenshotResponse>(R.layout.item_register_screenshot, BR.screenshotItem) {
            @Override
            public void addListener(View root, RegisterScreenshotResponse itemData, int position) {
                super.addListener(root, itemData, position);
                root.findViewById(R.id.img_download_screenshot).setOnClickListener(view -> {
                    viewModel.downloadScreenshot(itemData, true, false, context);
                });
            }

            @Override
            public void clickListener(View root, RegisterScreenshotResponse itemData, int position) {
                super.clickListener(root, itemData, position);
                root.findViewById(R.id.img_selected).setOnClickListener(view -> {
                    if (viewModel.addSelectedScreenshot(itemData)) {
                        itemData.setIsUsedToReport(!itemData.getIsUsedToReport());
                    }
                });

                root.findViewById(R.id.img_delete).setOnClickListener(view -> {
                    viewModel.removeScreenshot(itemData, p -> {
                        screenshotAdapter.onItemDataChanged(viewModel.screenshotList.getValue());
                        if (FileUtil.exist(p.getLocalStoragePath()))
                            FileUtil.del(p.getLocalStoragePath());
                    });
                });
            }
        };
        dataBinding.recyclerViewScreenshotList.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
        dataBinding.recyclerViewScreenshotList.setHasFixedSize(true);
        dataBinding.recyclerViewScreenshotList.setAdapter(screenshotAdapter);
    }

    /**
     * 按钮事件触发
     */
    private void btnClickBind() {
        //滑动条
        dataBinding.sbNumber.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                changeImagePath(viewModel.selectedImage.getValue(), progress);
                dataBinding.imageViewDraw.setFrame(progress - 1);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //photoview
        dataBinding.imgShow.setMinimumScale(1.0f);
        dataBinding.imgShow.setMaximumScale(5.0f);
        dataBinding.imgShow.setOnMatrixChangeListener(rect -> {
            dataBinding.imgShow.getDisplayMatrix(matrix);
            dataBinding.imageViewDraw.setImageMatrix(matrix);
            matrix.getValues(myValues);
            KLog.e("X轴缩放比例", myValues[Matrix.MSCALE_X] + "");
            KLog.e("Y轴缩放比例", myValues[Matrix.MSCALE_Y] + "");
        });

        //上一帧
        dataBinding.btnPrevious.setOnClickListener(view -> {
            int value = dataBinding.sbNumber.getProgress();
            if (value - 1 > 0) {
                dataBinding.sbNumber.setProgress(value - 1);
                changeImagePath(viewModel.selectedImage.getValue(), value - 1);
            }
        });

        //下一帧
        dataBinding.btnNext.setOnClickListener(view -> {
            int value = dataBinding.sbNumber.getProgress();
            if (value + 1 <= dataBinding.sbNumber.getMax()) {
                dataBinding.sbNumber.setProgress(value + 1);
                changeImagePath(viewModel.selectedImage.getValue(), value + 1);
            }
        });

        //截图
        screenshotHandler();

        //测量
        dataBinding.btnMeasureStart.setOnClickListener(v -> {
            dataBinding.imageViewDraw.canDrawStart = true;
            dataBinding.imageViewDraw.canDrawEnd = false;
        });
        dataBinding.btnMeasureEnd.setOnClickListener(v -> {
            dataBinding.imageViewDraw.canDrawEnd = true;
            dataBinding.imageViewDraw.canDrawStart = false;
        });

        //清除
        dataBinding.btnClear.setOnClickListener(v -> {
            dataBinding.imageViewDraw.clearLine(viewModel.selectedImage.getValue().getId(), viewModel.selectedImageCurrentFrame.getValue() - 1);
        });

        dataBinding.btnOffset.setOnClickListener(v -> {
            boolean result = !viewModel.leftOffset.getValue();
            viewModel.leftOffset.postValue(result);
            if (result) {
                dataBinding.btnOffset.setImageResource(R.drawable.offset_left);
                dataBinding.imageViewDraw.setLeftOffset(true);
            } else {
                dataBinding.btnOffset.setImageResource(R.drawable.offset_right);
                dataBinding.imageViewDraw.setLeftOffset(false);
            }
        });

        //横竖屏切换
        dataBinding.btnSwitch.setOnClickListener(v -> {
            if (getActivity().getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            } else {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        });

        //质控
        qaHandler();

        //修改Parts
        imagePartChange();
    }

    /**
     * 截图处理
     */
    private void screenshotHandler() {
        dataBinding.btnScreenshot.setOnClickListener(view -> {
            if (viewModel.selectedImage.getValue() != null) {
                if (viewModel.selectedImage.getValue().getCanPlay() == false) {
                    viewModel.infoMsg.postValue("请下载影像再截图");
                    return;
                }
                String destinationFilePath = getContext().getExternalCacheDir() + "/temp/screenshot/" + new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE).format(viewModel.register.getValue().getCreateTime()) + "/" + viewModel.selectedImage.getValue().getRegisterId() + "/" + viewModel.selectedImage.getValue().getId() + "_" + (viewModel.selectedImageCurrentFrame.getValue() - 1) + ".jpeg";
                File file = new File(destinationFilePath);
                if (file.exists()) {
                    viewModel.infoMsg.postValue("截图已存在");
                    return;
                }
                RegisterScreenshotSaveRequest request = new RegisterScreenshotSaveRequest();
                request.setFrameIndex(viewModel.selectedImageCurrentFrame.getValue() - 1);
                request.setImageId(viewModel.selectedImage.getValue().getId());
                request.setRegisterId(viewModel.register.getValue().getId());
                request.setApplyNo(viewModel.register.getValue().getApplyNo());
                //如果没有绘制
                if (!dataBinding.imageViewDraw.hasDraw()) {
                    CustomDisposable.addDisposable(RetrofitMobileClient.getInstance().getService(RegisterService.class).saveScreenshot(request), returnObject -> {
                        if (returnObject.isSuccess()) {
                            viewModel.screenshot.postValue(returnObject.getData());
                            viewModel.screenshotSelectedList.getValue().clear();
                        } else {
                            viewModel.infoMsg.postValue(returnObject.getMessage());
                        }
                    }, throwable -> {
                        KLog.e(TAG, throwable.getMessage());
                        viewModel.infoMsg.postValue(throwable.getMessage());
                    });
                } else {
                    //图片保存到本地
                    saveBitmap(destinationFilePath);
                    dataBinding.imageViewDraw.reDraw(true);

                    //上传到服务端
                    File uploadFile = new File(destinationFilePath);
                    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
                    RequestBody imageIdBody = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(request.getImageId()));
                    RequestBody frameIndexBody = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(request.getFrameIndex()));
                    MultipartBody.Part body = MultipartBody.Part.createFormData("file", uploadFile.getName(), requestFile);
                    CustomDisposable.addDisposable(RetrofitMobileClient.getInstance().getService(RegisterService.class).upload(body, imageIdBody, frameIndexBody), returnObject -> {
                        if (returnObject.isSuccess()) {
                            viewModel.screenshot.postValue(returnObject.getData());
                            viewModel.screenshotSelectedList.getValue().clear();
                        } else {
                            viewModel.infoMsg.postValue(returnObject.getMessage());
                        }
                    }, throwable -> {
                        KLog.e(TAG, throwable.getMessage());
                        viewModel.infoMsg.postValue(throwable.getMessage());
                    });
                }
            }
        });
    }

    /**
     * 质控处理
     */
    private void qaHandler() {
        dataBinding.btnQa.setOnClickListener(view -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            View dialogView = getLayoutInflater().inflate(R.layout.custom_alert_dialog, null);

            MultiSpinnerSearch multiSpinnerView = dialogView.findViewById(R.id.multiSpinnerView);
            multiSpinnerView.setSearchEnabled(false);
            multiSpinnerView.setShowSelectAllButton(false);
            multiSpinnerView.setColorSeparation(true);
            multiSpinnerView.setClearText("关闭");
            multiSpinnerView.setItems(QaFailedUtils.getDataList(), selectedItems -> {
                boolean isExists = selectedItems.stream().anyMatch(p -> p.isSelected());
                if (!isExists) {
                    return;
                }
                List<String> imageFailedReason = selectedItems.stream().filter(p -> p.isSelected()).map(p -> p.getName()).collect(Collectors.toList());
                String imageFailedReasonString = String.join(";", imageFailedReason);
                viewModel.register.getValue().setImageQaScore(1);
                viewModel.register.getValue().setImageFailedReason(imageFailedReasonString);
                CustomDisposable.addDisposable(RetrofitMobileClient.getInstance().getService(RegisterService.class).qa(new RegisterQaRequest(viewModel.register.getValue())), returnObject -> {
                    if (returnObject.isSuccess()) {
                        viewModel.register.getValue().setScreeningStatus(returnObject.getData().getScreeningStatus());
                        viewModel.register.getValue().setVersion(returnObject.getData().getVersion());
                        dialog.dismiss();
                        context.recreate();
                    } else {
                        viewModel.infoMsg.postValue(returnObject.getMessage());
                    }
                }, throwable -> {
                    KLog.e(TAG, throwable.getMessage());
                    viewModel.infoMsg.postValue(throwable.getMessage());
                });
            });

            dialogView.findViewById(R.id.btn_qa_best).setOnClickListener(v -> {
                multiSpinnerView.setVisibility(View.GONE);
                viewModel.register.getValue().setImageQaScore(1);
                jumpToReport(3);
            });
            dialogView.findViewById(R.id.btn_qa_better).setOnClickListener(v -> {
                multiSpinnerView.setVisibility(View.GONE);
                jumpToReport(2);
            });
            dialogView.findViewById(R.id.btn_qa_cha).setOnClickListener(v -> {
                multiSpinnerView.setVisibility(View.VISIBLE);
            });
            dialogView.findViewById(R.id.img_pop_close).setOnClickListener(v -> {
                dialog.dismiss();
            });
            builder.setView(dialogView);
            dialog = builder.create();
            dialog.show();
        });
    }

    /**
     * 影像Part修改
     */
    private void imagePartChange() {
        dataBinding.btnModify.setOnClickListener(view -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            View dialogView = getLayoutInflater().inflate(R.layout.custom_image_edit, null);
            dialogView.findViewById(R.id.image_item_edit_right).setOnClickListener(v -> {
                if (viewModel.selectedImage.getValue().getParts() == ImagePart.LEFT || viewModel.selectedImage.getValue().getParts() == ImagePart.LEFTLOBE)
                    return;
                RegisterImageChangeRequest request = new RegisterImageChangeRequest();
                request.setRegisterId(viewModel.register.getValue().getId());
                request.setApplyNo(viewModel.register.getValue().getApplyNo());
                request.setImageId(viewModel.selectedImage.getValue().getId());
                request.setParts(ImagePart.LEFT);
                CustomDisposable.addDisposable(RetrofitMobileClient.getInstance().getService(RegisterService.class).changePart(request), returnObject -> {
                    if (returnObject != null && returnObject.isSuccess()) {
                        RegisterImageResponse imageResponse = viewModel.selectedImage.getValue();
                        imageResponse.setParts(returnObject.getData());
                        List<RegisterImageResponse> imageList = viewModel.imageList.getValue();
                        int index = imageList.indexOf(viewModel.selectedImage.getValue());
                        if (index >= 0) {
                            imageList.set(index, imageResponse);
                            viewModel.selectedImage.postValue(imageResponse);
                            viewModel.imageList.postValue(imageList);
                        }
                        dialog.dismiss();
                    }
                });
            });
            dialogView.findViewById(R.id.image_item_edit_left).setOnClickListener(v -> {
                if (viewModel.selectedImage.getValue().getParts() == ImagePart.RIGHT || viewModel.selectedImage.getValue().getParts() == ImagePart.RIGHTLOBE)
                    return;
                RegisterImageChangeRequest request = new RegisterImageChangeRequest();
                request.setRegisterId(viewModel.register.getValue().getId());
                request.setApplyNo(viewModel.register.getValue().getApplyNo());
                request.setImageId(viewModel.selectedImage.getValue().getId());
                request.setParts(ImagePart.RIGHT);
                CustomDisposable.addDisposable(RetrofitMobileClient.getInstance().getService(RegisterService.class).changePart(request), returnObject -> {
                    if (returnObject != null && returnObject.isSuccess()) {
                        RegisterImageResponse imageResponse = viewModel.selectedImage.getValue();
                        imageResponse.setParts(returnObject.getData());
                        List<RegisterImageResponse> imageList = viewModel.imageList.getValue();
                        int index = imageList.indexOf(viewModel.selectedImage.getValue());
                        if (index >= 0) {
                            imageList.set(index, imageResponse);
                            viewModel.selectedImage.postValue(imageResponse);
                            viewModel.imageList.postValue(imageList);
                        }
                        dialog.dismiss();
                    }
                });
            });
            dialogView.findViewById(R.id.image_item_close).setOnClickListener(v -> {
                dialog.dismiss();
            });
            builder.setView(dialogView);
            dialog = builder.create();
            dialog.show();
        });
    }

    /**
     * 更改图片路径
     *
     * @param progress
     */
    private void changeImagePath(RegisterImageResponse imageResponse, int progress) {
        if (imageResponse != null) {
            int index = imageResponse.getLocalPath().lastIndexOf("/");
            String path = imageResponse.getLocalPath().substring(0, index) + "/" + (progress - 1) + ".jpeg";
            imageResponse.setLocalPath(path);
            dataBinding.imgShow.setImageBitmap(BitmapFactory.decodeFile(imageResponse.getLocalPath()));
            viewModel.selectedImageCurrentFrame.postValue(progress);
            viewModel.selectedImageLocalPath.postValue(path);
        }
    }

    /**
     * 弹出质控
     *
     * @param score
     */
    private void jumpToReport(int score) {
        //影像筛选
        Optional<RegisterImageResponse> optionalImageR = viewModel.imageList.getValue().stream().filter(p -> p.getParts() == ImagePart.RIGHT || p.getParts() == ImagePart.RIGHTLOBE).findFirst();
        Optional<RegisterImageResponse> optionalImageL = viewModel.imageList.getValue().stream().filter(p -> p.getParts() == ImagePart.LEFT || p.getParts() == ImagePart.LEFTLOBE).findFirst();

        //截图筛选
        Optional<RegisterScreenshotResponse> optionalValue1 = viewModel.screenshotSelectedList.getValue().stream().filter(p -> p.getParts() == ImagePart.RIGHT || p.getParts() == ImagePart.RIGHTLOBE).findFirst();
        Optional<RegisterScreenshotResponse> optionalValue2 = viewModel.screenshotSelectedList.getValue().stream().filter(p -> p.getParts() == ImagePart.LEFT || p.getParts() == ImagePart.LEFTLOBE).findFirst();

        // 左右齐全的逻辑
        if (score > 1) {
            if (viewModel.register.getValue().getAllowSingleSide() == false) {
                if (!optionalValue1.isPresent()) {
                    viewModel.infoMsg.postValue("右侧截图没有");
                    return;
                }
                if (!optionalValue2.isPresent()) {
                    viewModel.infoMsg.postValue("左侧截图没有");
                    return;
                }
            } else if (viewModel.register.getValue().getAllowSingleSide() == true) { //只有一侧的逻辑
                if (!(optionalValue1.isPresent() || optionalValue2.isPresent())) {
                    viewModel.infoMsg.postValue("请选择截图");
                    return;
                }
            }
        }

        Integer value = viewModel.register.getValue().getScreeningStatus().ordinal();
        if (value <= 2) {
            viewModel.register.getValue().setImageQaScore(score);
            viewModel.register.getValue().setImageFailedReason(null);
            CustomDisposable.addDisposable(RetrofitMobileClient.getInstance().getService(RegisterService.class).qa(new RegisterQaRequest(viewModel.register.getValue())), returnObject -> {
                if (returnObject.isSuccess()) {
                    viewModel.register.getValue().setScreeningStatus(returnObject.getData().getScreeningStatus());
                    viewModel.register.getValue().setVersion(returnObject.getData().getVersion());
                    dialog.dismiss();
                    if (optionalValue1.isPresent() && optionalValue2.isPresent()) {
                        jumpToReportActivity(optionalValue1.get(), optionalValue2.get());
                    } else {
                        if (optionalValue1.isPresent()) {
                            jumpToReportActivity(optionalValue1.get(), null);
                        } else {
                            jumpToReportActivity(null, optionalValue2.get());
                        }
                    }
                } else {
                    viewModel.infoMsg.postValue(returnObject.getMessage());
                }
            }, throwable -> {
                KLog.e(TAG, throwable.getMessage());
                viewModel.infoMsg.postValue(throwable.getMessage());
            });
        } else {
            dialog.dismiss();
            if (optionalValue1.isPresent() && optionalValue2.isPresent()) {
                jumpToReportActivity(optionalValue1.get(), optionalValue2.get());
            } else {
                if (optionalValue1.isPresent()) {
                    jumpToReportActivity(optionalValue1.get(), null);
                } else {
                    jumpToReportActivity(null, optionalValue2.get());
                }
            }
        }
    }

    /**
     * 向报告页面传参
     *
     * @param screenshot1
     * @param screenshot2
     */
    private void jumpToReportActivity(RegisterScreenshotResponse screenshot1, RegisterScreenshotResponse screenshot2) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.REGISTER_INFO, viewModel.register.getValue());
        bundle.putInt(Constants.SCREENING_TYPE, viewModel.register.getValue().getScreeningType().ordinal());
        if (screenshot1 != null) bundle.putSerializable(Constants.SCREENSHOT1, screenshot1);
        if (screenshot2 != null) bundle.putSerializable(Constants.SCREENSHOT2, screenshot2);
        Intent intent = new Intent(getActivity(), ReportActivity.class);
        intent.putExtra(Constants.REGISTER, bundle);
        startActivity(intent);
    }

    /**
     * 保存到本地
     *
     * @param localPath
     */
    private void saveBitmap(String localPath) {
        //始终恢复到原始状态保存
        dataBinding.imgShow.setScale(1.0f);
        dataBinding.imgShow.refreshDrawableState();

        //获取图片的宽高
        int width = dataBinding.imgShow.getWidth();
        int height = dataBinding.imgShow.getHeight();

        //创建canvas
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        //绘制图像
        dataBinding.imgShow.layout(0, 0, width, height);
        dataBinding.imgShow.draw(canvas);

        //绘制线条 如果view没有设置为透明 请设置为透明
        dataBinding.imageViewDraw.setBackgroundColor(Color.TRANSPARENT);
        dataBinding.imageViewDraw.layout(0, 0, width, height);
        dataBinding.imageViewDraw.draw(canvas);

        PathUtils.checkDirectory(localPath);
        File file = new File(localPath);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}